package com.binvshe.binvshe.opus;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.app.MyApplication;
import com.binvshe.binvshe.app.home.CommentActivity;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.usercenter.UserCenterActivity;
import com.binvshe.binvshe.mine.view.ThumbUpView;
import com.binvshe.binvshe.organization.ClubCenterActivity;
import com.binvshe.binvshe.organization.entity.ClubEntity;
import com.binvshe.binvshe.organization.entity.OpusListEntity;
import com.binvshe.binvshe.organization.tag.TagBean;
import com.bumptech.glide.Glide;
import com.cncn.youmengsharelib.ShareData;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.share.BaseShareFragment;
import com.pachong.android.framework.share.SharePlatformsFragment;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/9/21
 * 作品详情
 */

public class OpusDetailActivity extends BaseActivity implements ThumbUpView.OnThumbUp {
    private static final String KEY_OPUSID = "OPUSID";
    private static final int shareReqCode = 442;
    private boolean mIsLike;

    @InjectExtra(KEY_OPUSID)
    int mOpusID;

    @Bind(R.id.civUserHead)
    CircleImageView mCivUserHead;
    @Bind(R.id.tvUserName)
    TextView mTvUserName;
    @Bind(R.id.btnAttention)
    Button mBtnAttention;
    @Bind(R.id.relytUserPart)
    RelativeLayout mRelytUserPart;
    @Bind(R.id.tvOpusTitle)
    TextView mTvOpusTitle;
    @Bind(R.id.tagfllyt)
    TagFlowLayout mTagfllyt;
    @Bind(R.id.tvOpusContent)
    TextView mTvOpusContent;
    @Bind(R.id.linlytImages)
    LinearLayout mLinlytImages;
    @Bind(R.id.relytContentPart)
    RelativeLayout mRelytContentPart;
    @Bind(R.id.relytClubPart)
    RelativeLayout mRelytClubPart;
    @Bind(R.id.civClubHead)
    CircleImageView mCivClubHead;
    @Bind(R.id.tvClubName)
    TextView mTvClubName;
    @Bind(R.id.tvClubNum)
    TextView mTvClubNum;
    @Bind(R.id.tvClubPlace)
    TextView mTvClubPlace;
    @Bind(R.id.tvClubDesc)
    TextView mTvClubDesc;
    @Bind(R.id.btnCommentJ)
    TextView mTvCommentJ;
    @Bind(R.id.btnComment)
    ImageView mImgComment;
    @Bind(R.id.imgCommentCount)
    TextView mImgCommentCount;
    @Bind(R.id.btnLike)
    ImageView mImgLike;
    @Bind(R.id.imgLikeCount)
    TextView mImgLikeCount;
    @Bind(R.id.btnShare)
    ImageView mImgShare;
    @Bind(R.id.relytTouchPart)
    LinearLayout relytTouchPart;
    @Bind(R.id.tuvCollection)
    ThumbUpView mTuvCollection;
    @Bind(R.id.btnInClub)
    Button mBtnInClub;
    private int mCommentCount;
    private int mLikeCount;
    String mUserid = null;
    int mClubid = -1;
    TagAdapter mTagAdapter;
    ArrayList<TagBean> mTagDatas = new ArrayList<>();
    ShareData mShareData = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        Dart.inject(this);
        initTitle();
        initView();
        initTagPart();
        getOpusData();
    }

    @Override
    protected void onDestroy() {
        Glide.get(MyApplication.getAppContext()).clearMemory();
        super.onDestroy();
    }

    private void initView() {
        mTuvCollection.setOnThumbUp(this);
    }

    private void initTagPart() {
        mTagAdapter = new TagAdapter<TagBean>(mTagDatas) {
            @Override
            public View getView(FlowLayout parent, int position, TagBean o) {
                View view = getLayoutInflater().inflate(R.layout.item_tag, parent, false);
                TextView tvTagDel = (TextView) view.findViewById(R.id.tvTagDel);
                TextView tvTag = (TextView) view.findViewById(R.id.tvTag);
                o.setPositon(position);
                tvTag.setText(o.getTagContent());
                o.getTagBackGround(tvTag);
                tvTag.setTextColor(o.getTagTextColor());
                tvTagDel.setVisibility(View.GONE);
                return view;
            }
        };
        mTagfllyt.setAdapter(mTagAdapter);
    }

    private void initTitle() {
        enableBackButton();
        getCustomToolbar().addRightImageButton(R.mipmap.icon_morett_black, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IOSAlertListFragment iosAlertListFragment = new IOSAlertListFragment();
                List<String> dialoglist = new ArrayList<String>();
                dialoglist.add("举报");
                dialoglist.add("分享");
                iosAlertListFragment.setActionList(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0:
                                Toast.makeText(OpusDetailActivity.this, "举报成功", Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                if (mShareData != null) {
                                    BaseShareFragment fragment = SharePlatformsFragment.showShareFragment(OpusDetailActivity.this, mShareData);
                                    fragment.setShareListener(new ShareListener() {
                                        @Override
                                        public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                                            EasyToast.showToast(OpusDetailActivity.this, "分享成功");
                                        }

                                        @Override
                                        public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                                            EasyToast.showToast(OpusDetailActivity.this, "分享失败");
                                        }

                                        @Override
                                        public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                                            EasyToast.showToast(OpusDetailActivity.this, "分享取消");
                                        }
                                    });
                                }
                                break;
                        }
                    }
                }, dialoglist).show(getSupportFragmentManager());
            }
        });
    }

    public static void start(Context context, int opusID) {
        Intent starter = new Intent(context, OpusDetailActivity.class);
        starter.putExtra(KEY_OPUSID, opusID);
        context.startActivity(starter);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_opus_detail, container, false);
    }

    /**
     * 获取作品详情
     */
    public void getOpusData() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.GET_OPUS_DETAIL, mOpusID);
        request.get(url, null, new DataRequestListener<OpusDetailEntity>(OpusDetailEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(OpusDetailEntity o) {
                initDataView(o);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void initDataView(OpusDetailEntity o) {
        //<code>加载用户部分</code>
        Log.e("initDataView: ", "mOpusID" + mOpusID);
        IML.load(MyApplication.getAppContext(), mCivUserHead, o.getUser().getPortrait());
        mTvUserName.setText(o.getUser().getNickName() + "");
        mTvOpusTitle.setText(o.getTitle() + "");
        mTvOpusContent.setText(o.getContent() + "");
        mCommentCount = o.getComment_count();
        mLikeCount = o.getLike_count();
        mIsLike = o.isLike();
        mUserid = o.getUser().getUserId();
        if (o.isFavorite()) {
            mTuvCollection.setLike();
        } else {
            mTuvCollection.setUnlike();
        }
        if (mIsLike) {
            mImgLike.setImageResource(R.mipmap.icon_likett_p);
        } else {
            mImgLike.setImageResource(R.mipmap.icon_likebig);
        }
        if (mCommentCount == 0) {
            mImgCommentCount.setVisibility(View.GONE);
        } else {
            mImgCommentCount.setVisibility(View.VISIBLE);
            mImgCommentCount.setText(mCommentCount + "");
        }
        if (mLikeCount == 0) {
            mImgLikeCount.setVisibility(View.GONE);
        } else {
            mImgLikeCount.setVisibility(View.VISIBLE);
            mImgLikeCount.setText(mLikeCount + "");
        }
//        if(o.get)
        //<code>加载 image </code>
        for (OpusListEntity.ImagesEntity imgUrl : o.getImages()) {
            ImageView imageview = new ImageView(this);
            LinearLayout.LayoutParams params;
            if (/*有返回宽高*/imgUrl.getWidth() != 0 && imgUrl.getHeight() != 0) {
                float ratio = 1.0f * imgUrl.getHeight() / imgUrl.getWidth();
                int windowsWidth = getWindow().getWindowManager().getDefaultDisplay().getWidth();
                params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        (int) (windowsWidth * ratio));
                Log.d("Cain", "windowsWidth:" + windowsWidth);
                Log.d("Cain", "(windowsWidth*ratio):" + (windowsWidth * ratio));
            } else {//没有返回宽高
                Log.d("Cain", "没有返回宽高");
                params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
            }
            imageview.setLayoutParams(params);
            IML.loadDetail(MyApplication.getAppContext(), imageview, imgUrl.getUrl());
            mLinlytImages.addView(imageview);
        }
        //<code>加载用户部分</code>
        mTagDatas.addAll(o.getTags());
        mTagAdapter.notifyDataChanged();
        //<code>加载社团部分</code>
//        if (o.getClub() != null) {//作品所在社团
        if (o.getUser().getClub() != null) {
//            ClubEntity clubEntity = o.getClub();
            ClubEntity clubEntity = o.getUser().getClub();
            mClubid = clubEntity.getId();
            mTvClubName.setText(clubEntity.getName() + "");
            mTvClubNum.setText(getString(R.string.memberNum, clubEntity.getMember_count()));
            IML.load(MyApplication.getAppContext(), mCivClubHead, clubEntity.getPortrait());
            mTvClubPlace.setText(clubEntity.getCity() + "");
            if (!TextUtils.isEmpty(clubEntity.getSign())) {
                mTvClubDesc.setText(clubEntity.getSign() + "");
            }
            mRelytClubPart.setVisibility(View.VISIBLE);
        } else {//未加入社团
            mRelytClubPart.setVisibility(View.GONE);
        }
        initShareContent(o);
    }

    private void initShareContent(OpusDetailEntity o) {
        String articleUrl = String.format("http://app.binvshe.com/static/app/index.html#/article/%1$s", mOpusID);
//        mShareData = new ShareData(o.getImages().get(0).getUrl(), o.getTitle(), o.getContent(), articleUrl);
    }

    @OnClick({R.id.relytUserPart, R.id.relytClubPart, R.id.btnCommentJ, R.id.btnComment, R.id.btnLike, R.id.btnShare})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.relytUserPart:
                if (!TextUtils.isEmpty(mUserid))
                    UserCenterActivity.start(this, mUserid);
                break;
            case R.id.relytClubPart:
                if (mClubid != -1) {
                    ClubCenterActivity.start(this, mClubid);
                }
                break;
            case R.id.btnCommentJ:
                CommentActivity.start(this, mOpusID, true);
                break;
            case R.id.btnComment:
                CommentActivity.start(this, mOpusID, false);
                break;
            case R.id.btnLike:
                setLikeView();
                break;
            case R.id.btnShare:
                if (mShareData != null) {
                    BaseShareFragment fragment = SharePlatformsFragment.showShareFragment(OpusDetailActivity.this, mShareData);
                    fragment.setShareListener(new ShareListener() {
                        @Override
                        public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailActivity.this, "分享成功");
                        }

                        @Override
                        public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailActivity.this, "分享失败");
                        }

                        @Override
                        public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailActivity.this, "分享取消");
                        }
                    });
                }
                break;
        }
    }

    /**
     * 获取点赞数据
     */
    private void setLikeView() {
        MyHttpRequest request = new MyHttpRequest(OpusDetailActivity.this);
        String url = String.format(UrlCenter.LIKE, "article", mOpusID);
        UrlParams urlParams = new UrlParams();
        if (!mIsLike) {
            request.post(url, urlParams, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    mImgLike.setImageResource(R.mipmap.icon_likebig_p);
                    mIsLike = true;
                    mLikeCount = mLikeCount + 1;
                    if (mLikeCount == 0) {
                        mImgLikeCount.setVisibility(View.GONE);
                    } else {
                        mImgLikeCount.setVisibility(View.VISIBLE);
                        mImgLikeCount.setText(mLikeCount + "");
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(OpusDetailActivity.this, strMsg);
                }
            });
        } else {
            request.delete(url, urlParams, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    mImgLike.setImageResource(R.mipmap.icon_likebig);
                    mIsLike = false;
                    mLikeCount = mLikeCount - 1;
                    if (mLikeCount == 0) {
                        mImgLikeCount.setVisibility(View.GONE);
                    } else {
                        mImgLikeCount.setVisibility(View.VISIBLE);
                        mImgLikeCount.setText(mLikeCount + "");
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(OpusDetailActivity.this, strMsg);
                }
            });
        }
    }

    /**
     * 收藏
     */
    private void addFavorite() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.EVENT_FAVORITE, "article", mOpusID);
        request.post(url, new UrlParams(), new DataRequestListener(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Object o) {
                mTuvCollection.setLike();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(OpusDetailActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    /**
     * 取消收藏
     */
    private void deleteFavorite() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.EVENT_FAVORITE, "article", mOpusID);
        request.delete(url, new UrlParams(), new DataRequestListener(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Object o) {
                mTuvCollection.setUnlike();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    @Override
    public void like(boolean like) {
        if (like) {
            addFavorite();
        } else {
            deleteFavorite();
        }
    }
}
